<script setup>
import axiosInstance from "../axios/index.js"
import { ElMessage } from "element-plus";
import { reactive, ref } from "vue";
import { useStudentStore } from "@/stores/student.js";
import router from "@/router/index.js";


const formData = reactive({
  telephone: '19959601148',
  code: ''
});

//倒计时
const countdown = ref(60);
//是否进入倒计时
const isCountDown = ref(false);
//按钮文本
const buttonText = ref("获取验证码");

//手机号校验
function validateTelephone(telephone) {
  const regex = /^1[3-9]\d{9}$/;
  return regex.test(telephone);
}

// 验证手机号是否已注册
// function validateRegister(telephone) {
//   axiosInstance.get(`/student/checkPhone?telephone=${telephone}`)
//       .then(res => {
//    // console.log(res.data.data)
//     if (res.data.data === false) {
//       return false;
//     }
//     return true;
//   })
// }

//发送验证码
function sendCode() {
  if (!formData.telephone) {
    ElMessage({
      type: "error",
      message: '请填写手机号码'
    })
    return;
  }

  if (!validateTelephone(formData.telephone)) {
    ElMessage({
      type: "error",
      message: "手机号格式不正确"
    })
    return;
  }

  //  调用 validateRegister 函数
  //   validateRegister(formData.telephone).then(isRegistered => {
  //     if (!isRegistered) {
  //       return; // 如果未注册或未绑定，则不执行后续操作
  //     }
  //     console.log(isRegistered);
  //   })
  axiosInstance.get(`/student/checkPhone?telephone=${formData.telephone}`)
    .then(res => {
      if (res.data.data == false) {
        console.log(false);
        
          router.push({path:'/phoneBind',query:{
            telephone:formData.telephone
          }})
      } else {
        if (isCountDown.value) {
          return; // 如果已经在倒计时中，则不执行
        }


        if (isCountDown.value) {
          return; // 如果已经在倒计时中，则不执行
        }

        isCountDown.value = true;//正在倒计时
        buttonText.value = `重新获取(${countdown.value})秒`;
        startCountdown();

        axiosInstance.post("/student/sendCode", { telephone: formData.telephone })
          .then(response => {
            ElMessage({
              type: 'success',
              message: '验证码发送成功'
            })
            console.log(response.data)
          })
          .catch(error => {
            ElMessage({
              type: 'error',
              message: '验证码发送失败',
            });
            console.log(error);
            resetButton(); // 如果发送失败，重置按钮状态
          })
      }
    })



  // if (isCountDown.value) {
  //   return; // 如果已经在倒计时中，则不执行
  // }


  // if (isCountDown.value) {
  //   return; // 如果已经在倒计时中，则不执行
  // }

  // isCountDown.value = true;//正在倒计时
  // buttonText.value = `重新获取(${countdown.value})秒`;
  // startCountdown();

  // axiosInstance.post("/student/sendCode", {telephone: formData.telephone})
  //     .then(response => {
  //       ElMessage({
  //         type: 'success',
  //         message: '验证码发送成功'
  //       })
  //       console.log(response.data)
  //     })
  //     .catch(error => {
  //       ElMessage({
  //         type: 'error',
  //         message: '验证码发送失败',
  //       });
  //       console.log(error);
  //       resetButton(); // 如果发送失败，重置按钮状态
  //     })
}

//开始倒计时
function startCountdown() {
  const interval = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
      buttonText.value = `重新获取${countdown.value}秒`
    } else {
      clearInterval(interval)
      resetButton()
    }
  }, 1000)
}

//重置按钮状态
function resetButton() {
  isCountDown.value = false;
  countdown.value = 60;
  buttonText.value = '获取验证码'
}

//登录
function login() {
  axiosInstance.post("/student/login2", {
    telephone: formData.telephone,
    code: formData.code,
  }, {}).then(response => {
    localStorage.setItem("frontToken", response.data.data)//放置token
    useStudentStore().getStudentInfoByPhone(formData.telephone)//获取学生信息
    ElMessage({
      type: 'success',
      message: '登录成功',
      duration: 1000,
      onClose: function () {
        router.push('/index')
      }
    })
  }).catch(error => {
    ElMessage({
      type: 'error',
      message: '登陆失败'
    })
    console.log(error)
  })
}
</script>
<template>
  <div class="login-phone-container">
    <div class="login-phone">
      <div class="nav">
        <div class="login-phone-title">
          <el-image class="logo"
            src="https://blb-manage.oss-cn-wuhan-lr.aliyuncs.com/f1c9d90e-837c-488d-8d21-17e948a7914c.svg"></el-image>
          <!--        <span class="phone-title">手机号登陆</span>-->
        </div>
        <div class="login-phone-form">
          <el-form :model="formData">
            <div class="login-form-item">
              <el-form-item label="手机号" prop="telephone">
                <el-input prefix-icon="Phone" v-model="formData.telephone" type="text" placeholder="请输入手机号"></el-input>
              </el-form-item>
              <el-form-item label="验证码" prop="code">
                <el-input prefix-icon="Key" style="width: 180px;" v-model="formData.code" type="text"
                  placeholder="请填写验证码"></el-input>
                <el-button :disabled="isCountDown" class="btn" @click="sendCode()">{{ buttonText }}</el-button>
              </el-form-item>
              <el-form-item class="login-of">
                <div @click="router.push('/login')">
                  找不到手机或手机号停用？进入学号密码登录
                </div>
              </el-form-item>
              <div class="all-btn">
                <el-button type="primary" @click="login()">登录</el-button>
              </div>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/*整体样式*/
.login-phone-container {
  width: 100vw;
  display: flex;
  flex: 1;
  justify-content: center;
  align-items: center;
  height: 100%;
  //background: linear-gradient(125deg, #d5dee7, #ffafbd, #ffc3a0, #d9afd9, #97d9e1);
  background: linear-gradient(158deg, #E0C3FC 30%, #8EC5FC 70%);
  background-size: contain;
}

.login-phone-container .login-phone {
  width: 400px;
  position: relative;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(23px);
  box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
}

/*标题*/
.login-phone-container .login-phone-title {
  text-align: center;
  align-items: center;
  position: absolute;
  left: 0;
  right: 0;
  //bottom: 160px;
}

/*.login-phone-container .login-phone-title .phone-title{
  font-size: 50px;
  color: #333;
  font-weight: 10;
  font-family:Simsun;
}*/
.login-phone {
  width: 400px;
  height: 360px;
  position: relative;
  background: rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(23px);
  margin-left: 40px;
  box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
}

.login-phone-container .login-phone .nav {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.login-phone-container .login-phone .nav .logo {
  width: 200px;
}

/*form表单整体*/
.login-phone-container .login-phone-form {
  width: 400px;
  display: flex;
  justify-content: center;
  margin-top: 100px;
}

.login-phone .login-phone-form .login-form-item .el-form-item {
  margin-bottom: 30px;
}

.login-phone .login-phone-form .login-form-item .el-form-item:nth-child(2) {
  margin-bottom: 0;
}

.login-phone .login-phone-form .login-form-item .el-form-item:nth-child(3) {
  margin-bottom: 5px;
}

.login-phone .login-phone-form .login-form-item .el-input:nth-child(0) {
  width: 280px;
}

.login-of div {
  cursor: pointer;
  color: #409eff;
  position: relative;
  left: 65px;
}

.login-of div:hover {
  color: #007bff;
}

/*按钮*/
.login-phone .login-phone-form .login-form-item .btn {
  background-color: #ccc;
  padding: 5px;
  height: 32px;
}

.login-phone .login-phone-form .login-form-item .btn:hover {
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
  color: black;
}

.all-btn {
  text-align: center;
}
</style>